/**
 * Copyright 2010-present Facebook.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.twodstar.photobattle;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.RequestBatch;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.nostra13.universalimageloader.cache.disc.impl.TotalSizeLimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.widget.Advanceable;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;


/**
 * Base class for a list element in the Scrumptious main display, consisting of an
 * icon to the left, and a two line display to the right.
 */
public class Element_BattleList 
{
	private static final int CAMERA = 0;
    private static final int GALLERY = 1;
    
    private static final int REQUEST_CAMERA = 512;
    private static final int REQUEST_PHOTO = 513;
    
    private static final String FILE_PREFIX = "photobattle_img_";
    private static final String FILE_SUFFIX = ".jpg";
    
    public static ParseObject m_CounterAttackParseObject = null;
     
	private Activity m_Activity;
    private BaseAdapter adapter;
    private Fragment m_HostFragment;

    private ParseObject m_ParseObj;
	private String m_PlayerID1;
	private String m_PlayerID2;
    private String m_URL_P1;
    private String m_URL_P2;
    private String m_PhotoID1;
    private String m_PhotoID2;    
    private String m_PlayerName1;
    private String m_PlayerName2;
    private String m_WinnerID;
    private int m_InitialLike_P2;
    private int m_Finished_Like1;
    private int m_Finished_Like2;
    private long m_StartDate;
    private long m_EndDate;
    private long m_CurrentCountDown;
    private boolean m_PhotoAvailible1;
    private boolean m_PhotoAvailible2;
    private boolean m_IsFinished;
    private boolean m_IsSetViewElements;
    
    private boolean m_CanLike1;
    private boolean m_CanLike2;
    
    private int m_LikeCount1;
    private int m_LikeCount2;
    private int m_BattleLike2;
    private boolean m_SavedWinnerID;
    
    
    private TextView m_TextView_TotalLike1;
    private TextView m_TextView_TotalLike2;
    private TextView m_TextView_BattleLike1;
    private TextView m_TextView_BattleLike2;
    private TextView m_TextView_CountDown;
    private ProgressBar m_ProgressBar;
    private Button m_BtnCounterAttack;
    
    private Uri tempUri = null;
  
  
    
    /**
     * Constructs a new list element.
     *
     * @param icon the drawable for the icon
     * @param text1 the first row of text
     * @param text2 the second row of text
     * @param requestCode the requestCode to start new Activities with
     */
    public Element_BattleList(Activity PActivity, 
    						 Fragment pFragment,
    						 ParseObject pParseObj,
    						 String PlayerID1, String PlayerID2,
    						 String URL_P1, String URL_P2, String PhotoID1, String PhotoID2, 
    						 String PlayerName1, String PlayerName2, String WinnerID, 
    						 int InitialLike_P2, int Finished_Like1, int Finished_Like2,
    						 long StartDate, long EndDate
    						) 
    {
    	m_Activity = PActivity;
    	m_HostFragment = pFragment;
    	
    	m_ParseObj = pParseObj;
    	m_PlayerID1 = PlayerID1;
    	m_PlayerID2 = PlayerID2;
    	m_URL_P1 = URL_P1;
    	m_URL_P2 = URL_P2;
    	m_PhotoID1 = PhotoID1;
        m_PhotoID2 = PhotoID2;    
    	m_PlayerName1 = PlayerName1;
    	m_PlayerName2 = PlayerName2;    
    	m_WinnerID = WinnerID;
    	m_InitialLike_P2 = InitialLike_P2;   	
    	m_Finished_Like1 = Finished_Like1;
    	m_Finished_Like2 = Finished_Like2;
    	m_StartDate = StartDate;
    	m_EndDate = EndDate;
    	m_CurrentCountDown = EndDate - SntpClient.GetTimeUTC();
    	
    	m_LikeCount1 = 0;
    	m_LikeCount2 = 0;
    	m_PhotoAvailible1 = false;
    	m_PhotoAvailible2 = false;
    	m_IsFinished = false;
    	m_CanLike1 = true;
        m_CanLike2 = true;
        m_IsSetViewElements = false;
        m_SavedWinnerID = false;
        
    	//Log.i("game", "m_Finished_Likes " + m_Finished_Like1 + " " + m_Finished_Like2);
    	if(WinnerID.equalsIgnoreCase("0") == true)
    	{    		
    	}
    	else
    	{
    		m_IsFinished = true;    		
    	}
       
    }
    
    public void SetViewElements(    							 
    							 TextView TextView_TotalLike1,
								 TextView TextView_TotalLike2,
								 TextView TextView_BattleLike1,
								 TextView TextView_BattleLike2,
								 TextView TextView_CountDown,
								 ProgressBar PB,
								 Button BtnCounterAttack
								 )
    {
    	//Log.i("game", "SetViewElements-----------------");
    	
    
    	m_IsSetViewElements = true;
    	m_TextView_TotalLike1 = TextView_TotalLike1;
        m_TextView_TotalLike2 = TextView_TotalLike2;
        m_TextView_BattleLike1 = TextView_BattleLike1;
        m_TextView_BattleLike2 = TextView_BattleLike2;
        m_TextView_CountDown = TextView_CountDown;
        m_ProgressBar = PB;
        m_BtnCounterAttack = BtnCounterAttack;
        
        if(m_BtnCounterAttack != null)
        {
        	m_BtnCounterAttack.setOnClickListener(getOnClickCounterAttack());
        	//m_BtnCounterAttack.setVisibility(View.GONE);
        }
        
        SetLikeCalculation();
        
        if(m_IsFinished)
        {
        	if(IsMe(m_WinnerID))
        	{
        		m_TextView_CountDown.setText("You Won!");
        	}
        	else
        	{
        	        	
	        	if(m_WinnerID.equalsIgnoreCase(m_PlayerID1) == true)
	        	{        		
	        		m_TextView_CountDown.setText("Winner: " + m_PlayerName1);
	        	}
	        	else if(m_WinnerID.equalsIgnoreCase(m_PlayerID2) == true)
	        	{
	        		m_TextView_CountDown.setText("Winner: " + m_PlayerName2);
	        	}
	        	else if((m_WinnerID.equalsIgnoreCase("1") == true))
	        		m_TextView_CountDown.setText("Draw");
        	}
        }
        
        if(m_PhotoAvailible1 && m_PhotoAvailible2)
        {
        	//SetLikeCalculation();
        }
    }
    
    
 
    
    private boolean IsMe(String ThisID)
    {
    	ParseUser PU = ParseUser.getCurrentUser();    	
    	if(PU != null)
    	{
    		String MyID = PU.getString("FBID");
    		if(MyID != null && MyID.isEmpty() == false)
    		{
    			if(MyID.equalsIgnoreCase(ThisID))
    				return true;
    		}
    	}
    	
    	return false;
    }

    /**
     * The Adapter associated with this list element (used for notifying that the
     * underlying dataset has changed).
     * @param adapter the adapter associated with this element
     */
    public void setAdapter(BaseAdapter padapter) 
    {
        this.adapter = padapter;
    }
    
    public BaseAdapter getAdapter() 
    {
        return this.adapter;
    }

    public ParseObject getParseObj()
    {
    	return m_ParseObj;
    }
      
    public String getPlayerID1() 
    {
        return m_PlayerID1;
    }
    
    public String getPlayerID2() 
    {
        return m_PlayerID2;
    }
    
    public String getURL_P1() 
    {
        return m_URL_P1;
    }
    
    public String getURL_P2() 
    {
        return m_URL_P2;
    }
    
    public String getPhotoID1() 
    {
        return m_PhotoID1;
    }
    
    public String getPhotoID2() 
    {
        return m_PhotoID2;
    }
    
    public String getPlayerName1() 
    {
        return m_PlayerName1;
    }
    
    public String getPlayerName2() 
    {
        return m_PlayerName2;
    }
    
    public int getInitialLikeP2()
    {
    	return m_InitialLike_P2;
    }
    
    public long getStartDate()
    {
    	return m_StartDate;
    }
    
    public long getEndDate()
    {
    	return m_EndDate;
    }
    
    public void SetCanLike1(boolean b)
    {
    	m_CanLike1 = b;
    }

    public void SetCanLike2(boolean b)
    {
    	m_CanLike2 = b;
    }
    
    public boolean GetCanLike1()
    {
    	return m_CanLike1;
    }
    
    public boolean GetCanLike2()
    {
    	return m_CanLike2;
    }
    
    public boolean GetIsSetViewElements()
    {
    	return m_IsSetViewElements;
    }
    
    public void SetLikeCount1(int LikeCount)
    {
    	m_LikeCount1 = LikeCount; 
    	m_PhotoAvailible1 = true;
    	m_CanLike1 = true;
    	SetLikeCalculation();
    	
    	//Log.i("game", "LikeCount " + m_PhotoID1 + " "  +  LikeCount);
    }
    
    public void SetLikeCount2(int LikeCount)
    {
    	m_LikeCount2 = LikeCount;
    	m_PhotoAvailible2 = true;
    	m_CanLike2 = true;
    	SetLikeCalculation();
    	
    	//Log.i("game", "LikeCount " + m_PhotoID2 + " "  +  LikeCount);
    }
    
    private void SetLikeCalculation()
    {
    	if(m_IsFinished)
    	{
    		SetLikeCalculationForFinishedBattle();
    		return;
    	}
    	
    	if(m_TextView_TotalLike1 != null)
    	{
    		//Log.i("game", "LikeCount " + m_PhotoID1 + " "  +  m_LikeCount1);
    		m_TextView_TotalLike1.setText("Total LIKEs: " + m_LikeCount1);
    	}
    	else
    	{
    		//Log.i("game", "m_TextView_TotalLike1 is null ");
    	}
    	
    	if(m_TextView_BattleLike1 != null)
    	{
    		m_TextView_BattleLike1.setText("");
    	}
    	
    	
    	m_BattleLike2 = 0;
    	if(m_TextView_TotalLike2 != null)
    	{
    		m_TextView_TotalLike2.setText("Total LIKEs: " + m_LikeCount2);
    		
    		
    		m_BattleLike2 = m_LikeCount2 -  (int)( m_InitialLike_P2 * 0.5);
    		if(m_BattleLike2 < 0)
    			m_BattleLike2 = 0;
    		m_TextView_BattleLike2.setText("Battle LIKEs: " + m_BattleLike2);
    	}
    	else
    	{
    		//Log.i("game", "m_TextView_TotalLike2 is null ");
    	}
    	
    	if(m_ProgressBar != null)
    	{
    		float Ratio = 0;
    		if( m_LikeCount1 + m_BattleLike2 > 0)
    		{
    			Ratio = (float)m_LikeCount1 / (float)(m_LikeCount1 + m_BattleLike2);    			
    		}
    		else if( m_LikeCount1 == 0)
    		{
    			Ratio = 0.5f;
    		}
    		else
    		{
    			Ratio = 1;
    		}
    		int P = (int)(Ratio * 100);
    		//Log.i("game", "Progress " + P);
    		m_ProgressBar.setProgress(P);
    	}
    	
    	if(adapter != null)
    		adapter.notifyDataSetChanged();
    }
    
    private void SetLikeCalculationForFinishedBattle()
    {
    	if(m_TextView_TotalLike1 != null)
    	{
    		m_TextView_TotalLike1.setText("Total LIKEs: " + m_LikeCount1);
    		m_TextView_BattleLike1.setText("Battle LIKEs: " + m_Finished_Like1);
    	}
    	
    	if(m_TextView_TotalLike2 != null)
    	{
    		m_TextView_TotalLike2.setText("Total LIKEs: " + m_LikeCount2);    		
    		m_TextView_BattleLike2.setText("Battle LIKEs: " + m_Finished_Like2);
    	}
    	
    	if(m_ProgressBar != null)
    	{
    		float Ratio = 0;
    		if(m_Finished_Like1 + m_Finished_Like2  > 0)
    		{
    			Ratio = (float)m_Finished_Like1 / (float)(m_Finished_Like1 + m_Finished_Like2);    	
    			//Log.i("game", "Ratio " + Ratio);
    		}
    		else if( m_Finished_Like1 == 0)
    		{
    			Ratio = 0.5f;
    		}
    		else
    		{
    			Ratio = 1;
    		}
    		int P = (int)(Ratio * 100);
    		
    		m_ProgressBar.setProgress(P);
    	}
    	
    	if(adapter != null)
    		adapter.notifyDataSetChanged();
    }
    
      
    protected View.OnClickListener getOnClickListenerLeft()
    {
    	 return new View.OnClickListener() 
         {
             @Override
             public void onClick(View view)
             {
                 //showPhotoChoice();
            	String url = "fb://photo/" +  m_PhotoID1;
         		Intent i = new Intent(Intent.ACTION_VIEW);
         		i.setData(Uri.parse(url));
         		m_Activity.startActivity(i);
         		
            	 
             }
         };
    }
    
    protected View.OnClickListener getOnClickListenerRight()
    {
    	 return new View.OnClickListener() 
         {
             @Override
             public void onClick(View view)
             {
            	String url = "fb://photo/" +  m_PhotoID2;
          		Intent i = new Intent(Intent.ACTION_VIEW);
          		i.setData(Uri.parse(url));
          		m_Activity.startActivity(i);
             }
         };
    }
    
    
    private View.OnClickListener getOnClickCounterAttack()
    {
    	return new View.OnClickListener() 
        {
            @Override
            public void onClick(View view)
            {
            	//String url = "fb://photo/" +  m_PhotoID2;
         		//Intent i = new Intent(Intent.ACTION_VIEW);
         		//i.setData(Uri.parse(url));
         		//m_Activity.startActivity(i);
            	m_CounterAttackParseObject = m_ParseObj;
            	OnClickCounterAttack();
            }
        };
    }
    
    private void OnClickCounterAttack()
    {
    	 AlertDialog.Builder builder = new AlertDialog.Builder(m_Activity);
         CharSequence camera = m_Activity.getResources().getString(R.string.action_photo_camera);
         CharSequence gallery = m_Activity.getResources().getString(R.string.action_photo_gallery);
         builder.setCancelable(true).
                 setItems(new CharSequence[] {camera, gallery}, new DialogInterface.OnClickListener()
                 {
                     @Override
                     public void onClick(DialogInterface dialogInterface, int i) 
                     {
                         if (i == CAMERA) 
                         {
                             startCameraActivity();
                         } 
                         else if (i == GALLERY) 
                         {
                             startGalleryActivity();
                         }
                     }
                 });
         builder.show();
    }
    
    private void startCameraActivity() 
    {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        tempUri = getTempUri();
        if (tempUri != null) 
        {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        }
        m_HostFragment.startActivityForResult(intent, REQUEST_CAMERA);
    }

    private void startGalleryActivity() 
    {
        tempUri = null;
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        String selectPicture = m_Activity.getResources().getString(R.string.select_picture);
        m_HostFragment.startActivityForResult(Intent.createChooser(intent, selectPicture), REQUEST_PHOTO);
    }
    
    private Uri getTempUri()
    {
        String imgFileName = FILE_PREFIX + System.currentTimeMillis() + FILE_SUFFIX;

        // Note: on an emulator, you might need to create the "Pictures" directory in /mnt/sdcard first
        //       % adb shell
        //       % mkdir /mnt/sdcard/Pictures
        File image = new File(
                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), imgFileName);
        return Uri.fromFile(image);
    }
   
     
    protected void notifyDataChanged() 
    {
    	if(adapter != null)
    		adapter.notifyDataSetChanged();
    }
    
    public void LoadImageFromURL(ImageView image, Boolean IsP1)
    {
    	
    	String image_url = "";
    	
    	if(IsP1)
    		image_url = m_URL_P1;
    	else
    		image_url = m_URL_P2;
    	
    	// Get singletone instance of ImageLoader
    	
        ImageLoader imageLoader = ImageLoader.getInstance();
        // Initialize ImageLoader with configuration. Do it once.
        imageLoader.init(ImageLoaderConfiguration.createDefault(image.getContext()) );
        // Load and display image asynchronously
 
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                    .showStubImage(R.drawable.action_people) //this is the image that will be displayed if download fails
		            .cacheInMemory()
		            .cacheOnDisc()
		            .build();
 
        imageLoader.displayImage(image_url, image, options);
    	
    }
    
    public void Tick(int Delta)
    {
    	m_CurrentCountDown  -= (Delta * 1000);
    	
    	if(m_CurrentCountDown <= 0)
    	{
    		if(m_SavedWinnerID == false && m_ParseObj != null)
    		{
    			m_SavedWinnerID = true;
	    		// save it to database and refresh battle list
	    		String WinnerID = "1";
	    		if(m_LikeCount1 > m_BattleLike2)
	    			WinnerID = m_PlayerID1;
	    		else if(m_LikeCount1 < m_BattleLike2)
	    			WinnerID = m_PlayerID2;
	    		
	    		Log.i("game","Updating WinnerID -------------------------------");
	    		DataManager.UpdateWinnerID( m_ParseObj.getObjectId() , WinnerID , m_PlayerID1, m_PlayerID2, m_LikeCount1, m_BattleLike2);
    		}
    		
    		// now remove me.
    		
    		return;
    	}
    	
    	long TotalSecond = m_CurrentCountDown / 1000;
    	long Hour = TotalSecond / 3600;
    	
    	long Minute = (TotalSecond % 3600) / 60;
    	long Second =  (TotalSecond % 3600) % 60;
    	
    	
    	if(m_TextView_CountDown != null && m_IsFinished == false)
    	{
    		m_TextView_CountDown.setText("Battle Ends in: " + Hour + ":" + Minute + ":" + Second );
    		//Log.i("game","m_TextView_CountDown " + Hour + ":" + Minute + ":" + Second );
    		//Log.i("game",m_TextView_CountDown.getText().toString() );
    	}
    	else
    	{
    		//Log.i("game","m_TextView_CountDown is null");
    	}
    	
    	notifyDataChanged();
    }
    
    public void SaveWinner()
    {
    	
    }
    
    // Fix me
    public void RemoveIfPhotoNotAvailable()
    {
    	if(m_PhotoAvailible1 == false || m_PhotoAvailible2 == false)
    	{
    		if(adapter != null)
    		{
    			//Log.i("game", "remove " + m_PlayerName2 + " " + m_PhotoAvailible1 + " " + m_PhotoAvailible2 );
    			//@SuppressWarnings("unchecked")
				//ArrayAdapter<BattleListElement> AD = (ArrayAdapter<BattleListElement>) adapter;
    			//AD.clear();
    		}
    		
    	}
    }
    
    
    
}
